import 'package:boss/common/common.dart';
import 'package:boss/models/sku.dart';
import 'package:boss/models/store_menu.dart';
import 'package:boss/models/taste.dart';
import 'package:boss/provider/commodity_provider.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/commodity/categories/page/plusCommodityMode/page/plusCommodityByFormField/modal/printerModal/printer_modal.dart';
import 'package:boss/ui/page/commodity/categories/page/plusCommodityMode/page/plusCommodityByFormField/page/materialSetting/material_setting_page.dart';
import 'package:boss/ui/page/commodity/categories/page/plusCommodityMode/page/plusCommodityByFormField/page/skuSetting/sku_setting_page.dart';
import 'package:boss/ui/page/commodity/categories/page/plusCommodityMode/page/plusCommodityByFormField/page/tasteSetting/taste_setting_page.dart';
import 'package:boss/ui/page/commodity/categories/page/plusCommodityMode/page/plusCommodityByFormField/provider/plus_commodity_by_form_provider.dart';
import 'package:boss/ui/page/unit/page/pickerUnit/picker_unit_page.dart';
import 'package:boss/ui/widget/column_divier.dart';
import 'package:boss/ui/widget/custom_list_title.dart';
import 'package:boss/ui/widget/form/base_text_form_field.dart';
import 'package:boss/ui/widget/form/select_form_field.dart';
import 'package:boss/ui/widget/form_card.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/picker/imagePicker/image_picker.dart';
import 'package:boss/ui/widget/title_number_field.dart';
import 'package:boss/ui/widget/title_row_button.dart';
import 'package:boss/ui/widget/form/title_switch.dart';

import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

import 'plus_commodity_by_form_field_sku_header.dart';
import 'plus_commodity_by_form_field_sku_row.dart';
import 'plus_commodity_toggle_more_info_btn.dart';
import 'scan_icon.dart';

class PlusCommodityByFormFieldContent extends StatefulWidget {
  @override
  _PlusCommodityByFormFieldContentState createState() => _PlusCommodityByFormFieldContentState();
}

class _PlusCommodityByFormFieldContentState extends State<PlusCommodityByFormFieldContent> {
  bool _isShowMore = false;

  TextEditingController _barcodeController;

  @override
  void initState() {
    super.initState();

    _barcodeController = TextEditingController();

    final plusCommodityByFormProvider = Provider.of<PlusCommodityByFormProvider>(context, listen: false);
    _barcodeController.text = plusCommodityByFormProvider.commodity.commodityBarCode;

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      plusCommodityByFormProvider.initPrinter();
    });
  }

  @override
  void dispose() {
    _barcodeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<PlusCommodityByFormProvider>(
      builder: (context, plusCommodityByFormProvider, child) {
        List<Widget> children = [
          FormCard(
            children: <Widget>[
              BaseTextFormField(
                prefixText: '菜品名称',
                isRequired: true,
                hintText: '请输入',
                initialValue: plusCommodityByFormProvider.commodity.title,
                maxLength: 30,
                validator: (value) {
                  if (value == '') {
                    return '菜品名称不能为空，请输入菜品名称';
                  }

                  return null;
                },
                onChanged: (value) {
                  plusCommodityByFormProvider.setCommodityTitle(value);
                },
              ),
              Consumer<CommodityProvider>(
                builder: (context, commodityProvider, child) {
                  return SelectFormField<StoreMenu>(
                    title: '菜品分类',
                    hintText: '请选择',
                    items: commodityProvider.normalStoreMenus.map((menu) => SelectItem(value: menu, title: menu.menuName)).toList(),
                    value: plusCommodityByFormProvider.menu,
                    onChanged: (menu) {
                      plusCommodityByFormProvider.setCommodityMenu(menu);
                    },
                  );
                },
              ),
              if (plusCommodityByFormProvider.commodity.commoditySkuList.length == 0 && Constant.isTakeout)
                BaseTextFormField(
                  prefixText: '外卖售价',
                  isRequired: true,
                  hintText: '请输入',
                  suffixText: '元',
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                  initialValue: AmountUtil.price2String(plusCommodityByFormProvider.commodity.price),
                  maxLength: 10,
                  validator: (value) {
                    if (value == '') {
                      return '外卖售价不能为空';
                    }

                    return null;
                  },
                  onChanged: (value) {
                    plusCommodityByFormProvider.setCommodityPrice(value);
                  },
                ),
              if (plusCommodityByFormProvider.commodity.commoditySkuList.length == 0)
                BaseTextFormField(
                  prefixText: Constant.isTakeout ? '外卖原价' : '售卖价',
                  isRequired: !Constant.isTakeout,
                  hintText: '请输入',
                  suffixText: '元',
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                  initialValue: AmountUtil.price2String(
                      Constant.isTakeout ? plusCommodityByFormProvider.commodity.originalPrice : plusCommodityByFormProvider.commodity.price),
                  maxLength: 10,
                  validator: (value) {
                    if (value == '' && !Constant.isTakeout) {
                      return Constant.isTakeout ? '外卖原价不能为空' : '售卖价不能为空';
                    }

                    return null;
                  },
                  onChanged: (value) {
                    Constant.isTakeout ? plusCommodityByFormProvider.setCommodityOriginPrice(value) : plusCommodityByFormProvider.setCommodityPrice(value);
                  },
                ),
              if (plusCommodityByFormProvider.commodity.commoditySkuList.length == 0 && !Constant.isTakeout)
                BaseTextFormField(
                  prefixText: '会员价',
                  hintText: '请输入',
                  suffixText: '元',
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  inputFormatters: [FilteringTextInputFormatter.allow(RegUtil.numberReg)],
                  initialValue: AmountUtil.price2String(plusCommodityByFormProvider.commodity.memberPrice),
                  maxLength: 10,
                  onChanged: (value) {
                    plusCommodityByFormProvider.setCommodityVipPrice(value);
                  },
                ),
              if (Constant.isTakeout)
                BaseTextFormField(
                  prefixText: '限购份数',
                  hintText: '请输入',
                  suffixText: '份',
                  keyboardType: TextInputType.number,
                  inputFormatters: [FilteringTextInputFormatter.allow(RegExp('[1-9]'))],
                  initialValue: plusCommodityByFormProvider.commodity?.buyCount?.toString(),
                  maxLength: 8,
                  onChanged: (value) {
                    plusCommodityByFormProvider.setCommodityCount(value);
                  },
                ),
              if (!plusCommodityByFormProvider.commodity.isWeighCommodity)
                CustomListTitle(
                  title: '多规格设置',
                  trailing: LabelButton(
                    title: '+新增规格',
                    textStyle: TextStyleConstant().blue_28,
                    onTap: () async {
                      var result = await Navigator.pushNamed(context, SkuSettingPage.pageName, arguments: {
                        'skus': plusCommodityByFormProvider.commodity.commoditySkuList.map((item) => Sku.fromJson(item.toJson())).toList(),
                        'price': plusCommodityByFormProvider.commodity.price,
                        'salePrice': plusCommodityByFormProvider.commodity.originalPrice,
                        'vipPrice': plusCommodityByFormProvider.commodity.memberPrice,
                      });
                      if (result != null) {
                        plusCommodityByFormProvider.setCommoditySkus(result);
                      }
                    },
                  ),
                ),
              if (plusCommodityByFormProvider.commodity.commoditySkuList.length > 0 && !plusCommodityByFormProvider.commodity.isWeighCommodity)
                Column(
                  children: <Widget>[
                    PlusCommodityByFormFieldSkuHeader(),
                    ...plusCommodityByFormProvider.commodity.commoditySkuList.map((sku) => PlusCommodityByFormFieldSkuRow(sku: sku)).toList()
                  ],
                )
            ],
          ),
          FormCard(
            children: <Widget>[
              if (!Constant.isTakeout)
                TitleSwitch(
                  title: '称重计量',
                  value: plusCommodityByFormProvider.commodity.isWeighCommodity,
                  onChanged: (flag) {
                    plusCommodityByFormProvider.toggleWeighCommodity();
                  },
                ),
              TitleRowButton(
                title: '口味做法',
                hintText: '去设置',
                value: plusCommodityByFormProvider.tasteName,
                onTap: () async {
                  var result = await Navigator.pushNamed(context, TasteSettingPage.pageName, arguments: {
                    'tastes': plusCommodityByFormProvider.commodity.commodityTasteList.map((item) => Taste.fromJson(item.toJson())).toList(),
                  });
                  if (result != null) {
                    plusCommodityByFormProvider.setCommodityTastes(result);
                  }
                },
              ),
              TitleRowButton(
                title: '加料配菜',
                hintText: '去设置',
                value: plusCommodityByFormProvider.materialName,
                onTap: () async {
                  if (plusCommodityByFormProvider.menu == null) {
                    toast('请先选择菜品分类');
                    return;
                  }

                  var result = await Navigator.pushNamed(context, MaterialSettingPage.pageName, arguments: {
                    'menu': StoreMenu.fromJson(plusCommodityByFormProvider.menu.toJson()),
                    'materials': plusCommodityByFormProvider.commodity.commodityMeterialList,
                    'meterialType': plusCommodityByFormProvider.commodity.meterialType,
                  }) as Map<String, dynamic>;

                  if (result != null) {
                    plusCommodityByFormProvider.setCommodityMaterial(result['meterials'], result['meterialType']);
                  }
                },
              ),
              TitleSwitch(
                title: '后厨打印',
                value: plusCommodityByFormProvider.commodity.isChefPrint,
                onChanged: (value) {
                  plusCommodityByFormProvider.toggleCommodityChefPrinter();
                },
              ),
              if (plusCommodityByFormProvider.commodity.isChefPrint)
                TitleRowButton(
                  title: '菜品打印机',
                  hintText: '去设置',
                  value: plusCommodityByFormProvider.commodity.deviceNames.join('|'),
                  onTap: () async {
                    var printer = await showPrinterModal(
                      context,
                      selectedDeviceId: plusCommodityByFormProvider.commodity.deviceIds,
                      printers: plusCommodityByFormProvider.printers,
                    );
                    if (printer != null) {
                      plusCommodityByFormProvider.setCommodityDevice(printer);
                    }
                  },
                ),
              TitleRowButton(
                title: '菜品图片',
                hintText: '请上传',
                subTitle: '所传图片仅在扫码点餐时展示给顾客,不会在收银机的点菜单中展示',
                onTap: () async {
                  var image = await ImagePicker.pickImage(context);
                  if (image != null) {
                    var imagePath = await UploadUtil.uploadImage(image);
                    if (imagePath != null) {
                      plusCommodityByFormProvider.setCommodityImage(imagePath);
                    }
                  }
                },
              ),
            ],
          ),
        ];

        if (_isShowMore) {
          children.add(FormCard(children: <Widget>[
            TitleRowButton(
              title: '单位',
              value: plusCommodityByFormProvider.commodity.unit,
              hintText: '请选择',
              onTap: () async {
                final value = await showPickerUnit(context);
                if (value != null) {
                  plusCommodityByFormProvider.setCommodityUnit(value);
                }
              },
            ),
            BaseTextFormField(
              controller: _barcodeController,
              prefixText: '商品条形码',
              hintText: '选填，可填写条形码或扫码',
              maxLength: 50,
              suffix: ScanIcon(
                onScan: (value) {
                  plusCommodityByFormProvider.setCommodityBarCode(value);
                  _barcodeController.text = value;
                },
              ),
              onChanged: (value) {
                plusCommodityByFormProvider.setCommodityBarCode(value);
              },
            ),
            BaseTextFormField(
              prefixText: '菜品编码',
              hintText: '选填，菜品编号',
              maxLength: 50,
              initialValue: plusCommodityByFormProvider.commodity.commodityCode,
              onChanged: (value) {
                plusCommodityByFormProvider.setCommodityCode(value);
              },
            ),
            TitleNumberField(
              title: '起售份数',
              value: plusCommodityByFormProvider.commodity.commodityMinPie,
              onChanged: (number) {
                plusCommodityByFormProvider.setCommodityMinPie(number);
              },
            ),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(
                    top: 39.w,
                  ),
                  child: Text(
                    '菜品描述',
                    style: TextStyleConstant().normal_1_28,
                  ),
                ),
                BaseTextFormField(
                  maxLines: null,
                  maxLength: 200,
                  textAlign: TextAlign.start,
                  hintText: '请输入菜品描述，字数不超过200字',
                  initialValue: plusCommodityByFormProvider.commodity.description,
                  onChanged: (value) {
                    plusCommodityByFormProvider.setCommodityDesc(value);
                  },
                ),
              ],
            ),
            TitleSwitch(
              title: '仅套餐售卖',
              value: plusCommodityByFormProvider.commodity.isPackaged,
              onChanged: (value) {
                plusCommodityByFormProvider.toggleCommodityPackaged();
              },
            ),
            TitleSwitch(
              title: '上架售卖',
              value: plusCommodityByFormProvider.commodity.isOnSale,
              onChanged: (value) {
                plusCommodityByFormProvider.toggleCommoditySale();
              },
            ),
            //外卖模块隐藏 扫码点餐
            Constant.isTakeout == true
                ? Container()
                : TitleSwitch(
                    title: '扫码点餐',
                    value: plusCommodityByFormProvider.commodity.isH5,
                    onChanged: (value) {
                      plusCommodityByFormProvider.toggleH5();
                    },
                  ),
          ]));
        }

        children.add(PlusCommodityToggleMoreInfoBtn(
          isOpen: _isShowMore,
          onTap: () {
            setState(() {
              _isShowMore = !_isShowMore;
            });
          },
        ));

        return Expanded(
          child: SingleChildScrollView(
            child: ColumnDivier(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: children,
            ),
          ),
        );
      },
    );
  }
}
